// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    initializeApp();
});

// 初始化应用
function initializeApp() {
    setupNavigation();
    loadAttractions();
    setupModal();
    loadRoutes();
}

// 设置导航功能
function setupNavigation() {
    const navLinks = document.querySelectorAll('.nav-link');
    const sections = document.querySelectorAll('.section');

    navLinks.forEach(link => {
        link.addEventListener('click', function(e) {
            e.preventDefault();
            const targetSection = this.getAttribute('href').substring(1);
            showSection(targetSection);

            // 更新导航链接状态
            navLinks.forEach(l => l.classList.remove('active'));
            this.classList.add('active');
        });
    });
}

// 显示指定区域
function showSection(sectionId) {
    const sections = document.querySelectorAll('.section');
    sections.forEach(section => {
        section.classList.remove('active');
    });

    const targetSection = document.getElementById(sectionId);
    if (targetSection) {
        targetSection.classList.add('active');
    }
}

// 加载景点数据
function loadAttractions() {
    const attractionsGrid = document.getElementById('attractionsGrid');
    if (!attractionsGrid) return;

    attractionsGrid.innerHTML = attractionsData.map(attraction => `
        <div class="attraction-card" onclick="showAttractionDetail(${attraction.id})">
            <div class="attraction-image">
                <img src="${attraction.image}" alt="${attraction.name}">
            </div>
            <div class="attraction-content">
                <h3 class="attraction-title">${attraction.name}</h3>
                <p class="attraction-description">${attraction.description}</p>
                <div class="attraction-tags">
                    ${attraction.tags.map(tag => `<span class="tag">${tag}</span>`).join('')}
                </div>
            </div>
        </div>
    `).join('');
}

// 显示景点详情
function showAttractionDetail(attractionId) {
    const attraction = attractionsData.find(a => a.id === attractionId);
    if (!attraction) return;

    const modal = document.getElementById('attractionModal');
    const modalContent = document.getElementById('modalContent');

    modalContent.innerHTML = `
        <div class="attraction-detail">
            <div class="detail-header">
                <h2>${attraction.name}</h2>
                <div class="rating">
                    <span class="stars">${'★'.repeat(Math.floor(attraction.rating))}</span>
                    <span class="rating-text">${attraction.rating}/5.0</span>
                </div>
            </div>
            <div class="detail-image">
                <img src="${attraction.image}" alt="${attraction.name}">
            </div>
            <div class="detail-info">
                <p class="detail-description">${attraction.description}</p>
                <div class="info-grid">
                    <div class="info-item">
                        <i class="fas fa-map-marker-alt"></i>
                        <span>位置：${attraction.location}</span>
                    </div>
                    <div class="info-item">
                        <i class="fas fa-clock"></i>
                        <span>开放时间：${attraction.openingHours}</span>
                    </div>
                    <div class="info-item">
                        <i class="fas fa-ticket-alt"></i>
                        <span>门票价格：${attraction.ticketPrice}</span>
                    </div>
                </div>
                <div class="detail-tags">
                    ${attraction.tags.map(tag => `<span class="tag">${tag}</span>`).join('')}
                </div>
            </div>
        </div>
    `;

    modal.style.display = 'block';
}

// 设置模态框功能
function setupModal() {
    const modal = document.getElementById('attractionModal');
    const closeBtn = document.querySelector('.close');

    closeBtn.addEventListener('click', function() {
        modal.style.display = 'none';
    });

    window.addEventListener('click', function(e) {
        if (e.target === modal) {
            modal.style.display = 'none';
        }
    });
}

// 初始化应用时加载经典路线
// function loadRoutes() {
//     const classicRoutesContainer = document.getElementById('classicRoutes');
//     if (!classicRoutesContainer) return;
//
//     // 加载经典路线
//     classicRoutesContainer.innerHTML = routesData.map(route => `
//         <div class="route-card">
//             <div class="route-header">
//                 <h3>${route.name}</h3>
//                 <span class="duration">${route.duration}</span>
//             </div>
//             <div class="route-stops">
//                 ${route.attractions.map(attraction => `
//                     <div class="stop">
//                         <i class="fas fa-map-marker-alt"></i>
//                         <span>${attraction}</span>
//                     </div>
//                 `).join('')}
//             </div>
//             <button class="route-button" onclick="showRouteDetail(${route.id})">查看详情</button>
//         </div>
//     `).join('');
// }
// function loadRoutes() {
//     const classicRoutesContainer = document.getElementById('classicRoutes');
//     const themeRoutesContainer = document.getElementById('themeRoutes'); // 新增
//
//     if (!classicRoutesContainer || !themeRoutesContainer) return; // 更新
//
//     // 加载经典路线
//     classicRoutesContainer.innerHTML = routesData
//         .filter(route => route.id <= 5) // 筛选原有经典路线
//         .map(route => `
//         <div class="route-card">
//             <div class="route-header">
//                 <h3>${route.name}</h3>
//                 <span class="duration">${route.duration}</span>
//             </div>
//             <div class="route-stops">
//                 ${route.attractions.map(attraction => `
//                     <div class="stop">
//                         <i class="fas fa-map-marker-alt"></i>
//                         <span>${attraction}</span>
//                     </div>
//                 `).join('')}
//             </div>
//             <button class="route-button" onclick="showRouteDetail(${route.id})">查看详情</button>
//         </div>
//     `).join('');
//
//     // 新增：加载主题路线
//     themeRoutesContainer.innerHTML = routesData
//         .filter(route => route.id >= 6) // 筛选主题路线
//         .map(route => `
//         <div class="route-card">
//             <div class="route-header">
//                 <h3>${route.name}</h3>
//                 <span class="duration">${route.duration}</span>
//             </div>
//             <div class="route-stops">
//                 ${route.attractions.map(attraction => `
//                     <div class="stop">
//                         <i class="fas fa-map-marker-alt"></i>
//                         <span>${attraction}</span>
//                     </div>
//                 `).join('')}
//             </div>
//             <div class="route-meta">
//                 <span><i class="fas fa-signal"></i> 难度：${route.difficulty}</span>
//                 <span><i class="fas fa-money-bill-wave"></i> 预算：${route.budget}元</span>
//             </div>
//             <button class="route-button" onclick="showRouteDetail(${route.id})">查看详情</button>
//         </div>
//     `).join('');
// }
function loadRoutes() {
    const classicRoutesContainer = document.getElementById('classicRoutes');
    if (!classicRoutesContainer) return;

    // 加载经典路线
    classicRoutesContainer.innerHTML = routesData.map(route => `
        <div class="route-card">
            <div class="route-header">
                <h3>${route.name}</h3>
                <span class="duration">${route.duration}</span>
            </div>
            <!-- 新增难度和预算信息 -->
            <div class="route-meta">
                <div><i class="fas fa-signal"></i> 难度：${route.difficulty}</div>
                <div><i class="fas fa-money-bill-wave"></i> 预算：${route.budget}元</div>
            </div>
            <div class="route-stops">
                ${route.attractions.map(attraction => `
                    <div class="stop">
                        <i class="fas fa-map-marker-alt"></i>
                        <span>${attraction}</span>
                    </div>
                `).join('')}
            </div>
            <button class="route-button" onclick="showRouteDetail(${route.id})">查看详情</button>
        </div>
    `).join('');
}

// 同时更新路线详情弹窗，显示更完整的信息
function showRouteDetail(routeId) {
    const route = routesData.find(r => r.id === routeId);
    if (!route) return;

    // 计算经典路线的总预算
    const totalBudget = calculateAttractionsTotal(route.attractions);

    alert(`路线详情：${route.name}
    难度：${route.difficulty}
    行程天数：${route.duration}
    预算：${totalBudget}元
    
    ${route.description}
    
    包含景点：
    ${route.attractions.join('、')}`);
}
// 修改获取建议景点数量的函数
function getSuggestedAttractionsCount(days) {
    // 对于5天及以上的行程，每天建议1-2个景点（避免景点数量过多）
    if (days >= 5) {
        return [Math.max(1, days * 1), days * 2];
    }
    // 3-4天每天建议2-3个景点
    else if (days >= 3) {
        return [days * 2, days * 3];
    }
    // 1-2天每天建议2-4个景点
    else {
        return [days * 2, days * 4];
    }
}

// 生成符合条件的路线（修复跳转问题）
function generateRoutesByConditions() {
    const budgetInput = document.getElementById('routeBudget');
    const durationInput = document.getElementById('routeDuration');

    const maxBudget = parseInt(budgetInput.value) || 0;
    const days = parseInt(durationInput.value) || 0;

    if (maxBudget <= 0 || days <= 0) {
        alert("请输入有效的预算金额和游玩天数");
        return;
    }

    // 根据天数获取建议景点数量范围
    const [minAttractions, maxAttractions] = getSuggestedAttractionsCount(days);

    // 筛选所有预算在范围内的景点
    const affordableAttractions = attractionsData
        .filter(att => att.budget <= maxBudget)
        .sort((a, b) => b.rating - a.rating); // 按评分排序

    // 生成可能的路线组合
    const possibleRoutes = [];

    // 尝试不同的景点组合
    for (let i = minAttractions; i <= maxAttractions; i++) {
        // 生成景点组合
        for (let j = 0; j <= affordableAttractions.length - i; j++) {
            const selectedAttractions = affordableAttractions.slice(j, j + i);
            const attractionNames = selectedAttractions.map(att => att.name);
            const totalBudget = calculateAttractionsTotal(attractionNames);

            if (totalBudget <= maxBudget) {
                // 提取景点标签并统计出现次数
                const tagCounts = {};
                selectedAttractions.forEach(att => {
                    att.tags.forEach(tag => {
                        tagCounts[tag] = (tagCounts[tag] || 0) + 1;
                    });
                });

                // 找到最主要的标签作为路线类型
                const mainTag = Object.entries(tagCounts).sort((a, b) => b[1] - a[1])[0]?.[0] || "综合路线";

                possibleRoutes.push({
                    id: possibleRoutes.length + 1,
                    name: `${mainTag}${days}日游`,
                    duration: `${days}天`,
                    attractions: attractionNames,
                    totalBudget: totalBudget,
                    description: `包含${i}个精选景点，总预算${totalBudget}元，适合${days}天游玩`
                });
            }
        }
    }

    // 去重并按预算排序
    const uniqueRoutes = [...new Map(possibleRoutes.map(route =>
        [route.attractions.join(','), route]
    )).values()].sort((a, b) => a.totalBudget - b.totalBudget);

    // 显示结果
    displayDynamicRoutes(uniqueRoutes, maxBudget, days);

    // 修复：确保滚动到个性化推荐路线区域
    setTimeout(() => { // 增加延迟确保DOM已更新
        // 更可靠的选择器：直接选择个性化推荐区域的标题
        const dynamicRoutesSection = document.querySelector('#routes .section-header:nth-child(3)');
        if (dynamicRoutesSection) {
            // 平滑滚动到目标区域
            dynamicRoutesSection.scrollIntoView({
                behavior: 'smooth',
                block: 'start'
            });
        } else {
            // 备选方案：直接滚动到结果容器
            const resultsContainer = document.getElementById('dynamicRoutes');
            if (resultsContainer) {
                resultsContainer.scrollIntoView({
                    behavior: 'smooth',
                    block: 'start'
                });
            }
        }
    }, 100); // 100ms延迟确保内容已渲染
}


// 显示动态生成的路线
function displayDynamicRoutes(routes, budget, days) {
    const container = document.getElementById('dynamicRoutes');

    if (routes.length === 0) {
        container.innerHTML = `
            <div class="route-hint" style="text-align: center; padding: 2rem; background: white; border-radius: 15px; box-shadow: 0 5px 20px rgba(0,0,0,0.1);">
                <i class="fas fa-exclamation-circle" style="font-size: 3rem; color: #f44336; margin-bottom: 1rem;"></i>
                <h3>未找到符合条件的路线</h3>
                <p style="margin-top: 1rem; color: #666;">请尝试调整预算或游玩天数</p>
            </div>
        `;
    } else {
        container.innerHTML = routes.map(route => `
            <div class="route-card">
                <div class="route-header">
                    <h3>${route.name}</h3>
                    <span class="duration">${route.duration}</span>
                </div>
                <div class="route-stops">
                    ${route.attractions.map(att => {
            const attData = attractionsData.find(a => a.name === att);
            return `
                            <div class="stop">
                                <i class="fas fa-map-marker-alt"></i>
                                <span>${att}（预算：${attData ? attData.budget : 0}元）</span>
                            </div>
                        `;
        }).join('')}
                </div>
                <p style="margin-bottom: 1rem; color: #666;"><strong>总预算：</strong>${route.totalBudget}元</p>
                <p style="margin-bottom: 1rem; color: #666;">${route.description}</p>
            </div>
        `).join('');
    }
}

// 计算景点预算总和
function calculateAttractionsTotal(attractionNames) {
    return attractionNames.reduce((total, name) => {
        const attraction = attractionsData.find(att => att.name === name);
        return total + (attraction ? attraction.budget : 0);
    }, 0);
}

// 路线详情功能
function showRouteDetail(routeId) {
    const route = routesData.find(r => r.id === routeId);
    if (!route) return;

    // 计算经典路线的总预算
    const totalBudget = calculateAttractionsTotal(route.attractions);

    alert(`路线详情：${route.name}\n\n${route.description}\n\n包含景点：${route.attractions.join('、')}\n\n预算：${totalBudget}元`);
}

// 根据预算筛选景点
function filterAttractionsByBudget(budget) {
    console.log("筛选预算:", budget); // 调试信息
    const filteredAttractions = attractionsData.filter(attraction => attraction.budget <= budget);
    const attractionsGrid = document.getElementById('attractionsGrid');
    if (!attractionsGrid) return;

    attractionsGrid.innerHTML = filteredAttractions.map(attraction => `
        <div class="attraction-card" onclick="showAttractionDetail(${attraction.id})">
            <div class="attraction-image">
                <img src="${attraction.image}" alt="${attraction.name}">
            </div>
            <div class="attraction-content">
                <h3 class="attraction-title">${attraction.name}</h3>
                <p class="attraction-description">${attraction.description}</p>
                <div class="attraction-tags">
                    ${attraction.tags.map(tag => `<span class="tag">${tag}</span>`).join('')}
                </div>
            </div>
        </div>
    `).join('');
}